﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static ATEGo.CmdField;
namespace ATEGo
{
    //———————————————————————【停止和取消】————————————————————————
    public partial class Executor
    {
        /// <summary>
        /// 执行停止
        /// </summary>
        private void FormStopAction()
        {
            WriteFlow_Stop();
            Action act = () =>
            {
                Action_Stop?.Invoke();
            };
            This_Form.Invoke(act);
        }
        /// <summary>
        /// 由用户主动引发停止
        /// </summary>
        public void Stop()
        {
            IsStop = true;
            Running_TCS.TrySetResult(false);
            Running_CTS.Cancel();
        }
        /// <summary>
        /// 是否停止执行
        /// </summary>
        private bool IsStop { get; set; } = false;
        /// <summary>
        /// 检查是否停止，并做相应的动作
        /// </summary>
        /// <returns></returns>
        private bool CheckAndStop()
        {
            if (IsStop)
            {
                FormStopAction();
                return true;
            }
            else
            {
                return false;
            }
        }

        #region 超时Timer
        /// <summary>
        /// 超时失败
        /// </summary>
        private System.Timers.Timer TimeOuter;
        private void TimerStart()
        {
            TimeOuter = new System.Timers.Timer();
            TimeOuter.Interval = Running_Cmd[timeOut].TimeToMS();
            TimeOuter.Elapsed += (sender, e) =>
            {
                TimerStop(true);
            };
            TimeOuter.Enabled = true;
            TimeOuter.AutoReset = true;
            TimeOuter.Start();
        }
        private void TimerStop(bool isFailed)
        {
            if (isFailed)
            {
                WriteFlow_Fail($"执行超时{Running_Cmd[timeOut].TimeToMS()}毫秒");
            }
            TimeOuter.Stop();
            TimeOuter.Enabled = false;
            TimeOuter.Close();
            IsReceiveEcho = false;
            if (isFailed)
            {
                //超时，默认执行fail
                Running_TCS.TrySetResult(false);
            }
        }
        #endregion
    }
}
